package com.qzdsoft.erpcloud.controller;

import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.qzdsoft.JWTProperties;
import com.qzdsoft.erpcloud.controller.common.SessionUtil;
import com.qzdsoft.erpcloud.domain.sys.LoginUser;
import com.qzdsoft.erpcloud.service.sys.Permission;
import com.qzdsoft.erpcloud.service.sys.RedisService;
import com.qzdsoft.erpcloud.service.sys.SysLoginService;
import com.qzdsoft.erpcloud.service.sys.SysMenuButtonService;
import com.qzdsoft.erpcloud.vo.sys.RegisterInfo;
import com.qzdsoft.utils.JsonUtils;
import com.qzdsoft.utils.JwtHelper;
import com.qzdsoft.utils.StringUtil;
import com.qzdsoft.utils.SysUtils;
import com.qzdsoft.utils.constant.RedisConstant;
import com.qzdsoft.utils.constant.SystemConstant;
import com.qzdsoft.vo.Response;
import com.qzdsoft.vo.ResultEnum;
import com.qzdsoft.vo.TypeInfo;

/**
 * Created by lifh on 16/10/15.
 */
@Controller
@RequestMapping("/")
public class LoginController extends BaseController{

    @Autowired
    private SysLoginService sysLoginService;
    
    @Autowired
    private SysMenuButtonService sysMenuButtonService;

    @Autowired
    private RedisService redisService;
    
    @Autowired
    private JWTProperties jWTProperties;
    

    /**
     *
     * @param request
     * @param model
     * @return
     */
    @RequestMapping("/login.html")
    public Object toLogin(HttpServletRequest request, Model model) {
        String key = SystemConstant.cxdlKey.concat(SessionUtil.getSessionId(request));
        Object obj = redisService.get(key);
        if(null != obj){
            redisService.del(key);
            request.removeAttribute(SystemConstant.cxdlKey);
            model.addAttribute(SystemConstant.cxdlKey, obj);
        }
        String cxdl = request.getParameter("cxdl");
        if(!StringUtil.isEmpty(cxdl)) {
            model.addAttribute("cxdl",cxdl);
        }
        return "login/login";
    }

    /**
     * 注册
     *
     * @param request
     * @param model
     * @return
     */
    @RequestMapping("/forget")
    public Object forget(HttpServletRequest request, Model model) {
        return "login/forget";
    }

    /**
     * 注册
     *
     * @param request
     * @param model
     * @return
     */
    @Permission(validate=false)
    @RequestMapping("/register")
    public ModelAndView register() {
        ModelAndView mv = new ModelAndView();
        mv.setViewName("login/register");
        return mv;
    }
    
    /**
     * 注册保存
     *
     * @param request
     * @return
     */
    @Permission(validate=false)
    @ResponseBody
    @RequestMapping("/registerSave")
    public Response<String> registerSave(RegisterInfo registerInfo) {
        return sysLoginService.registerSave(registerInfo);
    }
    

    /**
     * 执行登录
     *
     * @param request
     * @param name
     * @param password
     * @param mark
     * @return
     */
    @ResponseBody
    @RequestMapping("/login")
    public Object login(HttpServletResponse response,HttpServletRequest request, @RequestParam("name") String name, @RequestParam("password") String password, @RequestParam("mark") String mark) {
        if(StringUtils.isBlank(name)){
            return new Response(ResultEnum.ERROR.getCode(),"请输入用户名");
        }

        if(StringUtils.isBlank(password)){
            return new Response(ResultEnum.ERROR.getCode(),"请输入密码");
        }

        if(StringUtils.isBlank(mark)){
            return new Response(ResultEnum.ERROR.getCode(),"请输入验证码");
        }

        LoginUser sysLogin = sysLoginService.selectForLogin(name, SysUtils.string2MD5(password));
        if(null != sysLogin){

            Object smark = redisService.get(SysUtils.redisKaptcha(SessionUtil.getSessionId(request)));
            if(null == smark){
                return new Response(ResultEnum.ERROR.getCode(),"无法获取系统验证码信息或验证码过期!");
            } else {
                if(!smark.toString().equalsIgnoreCase(mark)){
                    return new Response(ResultEnum.ERROR.getCode(),"验证码输入错误,请重新输入");
                }
            }
            //SessionUtil.setLogged(request, sysLogin);
            sysLogin.setUuid(UUID.randomUUID().toString());//随机数用于单点登录验证
            String token = JwtHelper.createJWT(sysLogin.getId(), sysLogin.getCompanyId(), sysLogin.getPhone(),sysLogin.getUuid(),jWTProperties.getBase64Security(), -1);
            redisService.set(SysUtils.redisUserSessionId(sysLogin.getId()), JsonUtils.objectToJson(sysLogin), (int)jWTProperties.getTokenExpriseTime());
            List<TypeInfo> buttons = sysMenuButtonService.selectAuthorizedButton(sysLogin.getId());
            List<String> butIds = new ArrayList<>();
            for(TypeInfo but:buttons) {
                butIds.add(but.getCode());
            }
            Cookie cookie = new Cookie("authtoken", token);
            Cookie uidCookie = new Cookie("uid", sysLogin.getId().toString());
            response.addCookie(cookie);
            response.addCookie(uidCookie);
            return new Response<List<String>>(ResultEnum.SUCCESS,butIds);
        }
        return new Response(ResultEnum.ERROR.getCode(),"用户名或者密码错误，请重新输入!");
    }


    /**
     * 退出
     *
     * @param request
     * @param name
     * @param password
     * @return
     */
    @Permission(validate=false)
    @ResponseBody
    @RequestMapping("/logout")
    public Object logout(HttpServletResponse response,HttpServletRequest request, String name, String password) {
        //清除缓存
        Integer uid = getUid();
        redisService.del(SysUtils.redisUserSessionId(uid));
        redisService.del(RedisConstant.reidsAuthorizedUrl+"_"+uid);
        redisService.del(RedisConstant.redisButton+"_"+uid);
        Cookie cookies []= request.getCookies();
        for(Cookie c:cookies) {
            if("uid".equals(c.getName())||"authtoken".equals(c.getName())) {
                Cookie cookie = new Cookie("uid","");
                Cookie tokenCookie = new Cookie("authtoken", "");
                cookie.setMaxAge(0);
                tokenCookie.setMaxAge(0);
                response.addCookie(tokenCookie);
                response.addCookie(cookie);
            }
        }
        return new Response(ResultEnum.SUCCESS);
    }
}
